<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class RoomMember extends Model
{
    use HasFactory;

    protected $fillable = [
        'room_id',
        'user_id',
        'role',
        'joined_at',
        'last_active_at',
        'is_active',
        'settings',
        'is_pinned',
        'pinned_at',
        'last_visited_at',
    ];

    protected $casts = [
        'joined_at' => 'datetime',
        'last_active_at' => 'datetime',
        'is_active' => 'boolean',
        'settings' => 'array',
        'is_pinned' => 'boolean',
        'pinned_at' => 'datetime',
        'last_visited_at' => 'datetime',
    ];

    /**
     * 准备日期用于数组/JSON序列化
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 所属房间
     */
    public function room(): BelongsTo
    {
        return $this->belongsTo(Room::class);
    }

    /**
     * 所属用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 更新最后活跃时间
     */
    public function updateLastActiveAt(): void
    {
        $this->update(['last_active_at' => now()]);
    }

    /**
     * 检查是否是创建者
     */
    public function isCreator(): bool
    {
        return $this->role === 'creator';
    }

    /**
     * 检查是否是管理员
     */
    public function isAdmin(): bool
    {
        return in_array($this->role, ['creator', 'admin']);
    }

    /**
     * 检查是否是普通成员
     */
    public function isMember(): bool
    {
        return $this->role === 'member';
    }

    /**
     * 检查是否有权限管理房间
     */
    public function canManageRoom(): bool
    {
        return $this->isAdmin();
    }

    /**
     * 检查是否有权限添加菜品
     */
    public function canAddDishes(): bool
    {
        $settings = $this->room->settings ?? [];
        return $this->isAdmin() || ($settings['allowParticipantAdd'] ?? true);
    }

    /**
     * 检查是否有权限建议菜品
     */
    public function canSuggestDishes(): bool
    {
        $settings = $this->room->settings ?? [];
        return $this->isAdmin() || ($settings['allowParticipantSuggest'] ?? true);
    }

    /**
     * 按角色筛选
     */
    public function scopeByRole($query, string $role)
    {
        return $query->where('role', $role);
    }

    /**
     * 获取活跃成员
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 按房间筛选
     */
    public function scopeByRoom($query, int $roomId)
    {
        return $query->where('room_id', $roomId);
    }

    /**
     * 按用户筛选
     */
    public function scopeByUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * 设置置顶状态
     */
    public function pin(): void
    {
        $this->update([
            'is_pinned' => true,
            'pinned_at' => now(),
        ]);
    }

    /**
     * 取消置顶状态
     */
    public function unpin(): void
    {
        $this->update([
            'is_pinned' => false,
            'pinned_at' => null,
        ]);
    }

    /**
     * 更新最后访问时间
     */
    public function updateLastVisitedAt(): void
    {
        $this->update(['last_visited_at' => now()]);
    }

    /**
     * 检查是否已置顶
     */
    public function isPinned(): bool
    {
        return $this->is_pinned;
    }

    /**
     * 获取置顶的房间
     */
    public function scopePinned($query)
    {
        return $query->where('is_pinned', true);
    }

    /**
     * 按最后访问时间排序
     */
    public function scopeOrderByLastVisited($query, string $direction = 'desc')
    {
        return $query->orderBy('last_visited_at', $direction);
    }

    /**
     * 按置顶时间排序
     */
    public function scopeOrderByPinned($query, string $direction = 'desc')
    {
        return $query->orderBy('pinned_at', $direction);
    }
}